package collector.app.nexd.com.singlecollection.presenter.building;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.support.annotation.NonNull;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import collector.app.nexd.com.singlecollection.application.NexdApplication;
import collector.app.nexd.com.singlecollection.model.Mall;
import collector.app.nexd.com.singlecollection.presenter.db.NexdSqlOpenHelper;
import collector.app.nexd.com.singlecollection.presenter.db.TableContract;
import collector.app.nexd.com.singlecollection.presenter.network.HttpMethod;
import collector.app.nexd.com.singlecollection.util.UrlUtil;

/**
 * Created by xun on 2016/8/9.
 */
public class LoadBuildingPresenter implements LoadBuildingContract.Presenter {
    private final LoadBuildingContract.View buildingView;
    private HttpMethod httpMethod;
    private Context context;
    private NexdSqlOpenHelper databaseHelp;
    private List<Map<String, Object>> cityList;
    private static final String TAG = "LoadBuildingPresenter";

    public LoadBuildingPresenter(LoadBuildingContract.View buildingView) {
        this.buildingView = buildingView;
        this.context = (Context) buildingView;
        this.httpMethod = HttpMethod.getInstance(context);
        this.databaseHelp = NexdApplication.getInstance().getSqlHelper();
    }

    @Override
    public void init() {
        cityList = databaseHelp.selectCursorToList(databaseHelp.selectCursor("select * from " + TableContract.City.TABLE_NAME, null));
        if (cityList.size() > 0) {
            List<Mall> malls = loadMalls(cityList.get(0).get(TableContract.City.COLUMN_CITY_NAME).toString());
            if (cityList.size() > 0 && malls.size() > 0) {
                buildingView.querySuccess(cityList, malls);
            }
        }
    }


    public List<Mall> loadMalls(String cityName) {
        Cursor cursor = databaseHelp.selectCursor("select * from " + TableContract.Building.TABLE_NAME + " where " + TableContract.City.COLUMN_CITY_NAME + "=?", new String[]{cityName});
        List<Mall> malls = new ArrayList<>();
        if (cursor != null && cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                Mall mall = new Mall();
                mall.setBuildingCode(cursor.getString(cursor.getColumnIndex(TableContract.Building.COLUMN_BUILDING_CODE)));
                mall.setCnName(cursor.getString(cursor.getColumnIndex(TableContract.Building.COLUMN_BUILDING_NAME)));
                mall.setPyName(cursor.getString(cursor.getColumnIndex(TableContract.Building.COLUMN_BUILDING_NAME_PY)));
                mall.setCnCityName(cursor.getString(cursor.getColumnIndex(TableContract.Building.COLUMN_CITY_NAME)));
                mall.setPyCityName(cursor.getString(cursor.getColumnIndex(TableContract.Building.COLUMN_CITY_NAME_PY)));
                malls.add(mall);
            }
        }
        return malls;
    }



    private Map<String, String> cityMap = new HashMap<>();

    @Override
    public void loadData() {
        StringBuffer mallUrl = new StringBuffer(UrlUtil.BASE_IP);
        mallUrl.append(UrlUtil.BUILDING_URL);
        Map<String, String> params = new HashMap<>();
        params.put(UrlUtil.PARAMER_APPKEY, UrlUtil.APPKEY);
        httpMethod.execute(mallUrl.toString(), new HttpMethod.OnRequestListener() {
            @Override
            public void success(JSONArray data) throws JSONException {

                List<Mall> malls = getMallsFromHttp(data);


                databaseHelp.deleteAll(TableContract.City.TABLE_NAME);
                databaseHelp.deleteAll(TableContract.Building.TABLE_NAME);
                // 添加城市表

                addCitiesToDB();

                // 添加商场

                addMallsToDB(malls);

                init();
                buildingView.loadDataSuccess();

            }


            @Override
            public void requestError(String msg) {
                buildingView.printLog(msg);
                buildingView.loadDataFail();
            }

            @Override
            public void networkError(String msg) {
                buildingView.printLog(msg);
                buildingView.loadDataFail();
            }
        }, params, "malls");
    }

    private void addMallsToDB(List<Mall> malls) {
        for (int i = 0, len = malls.size(); i < len; i++) {
            Mall mall = malls.get(i);
            ContentValues mallValues = new ContentValues();
            mallValues.put(TableContract.Building.COLUMN_CITY_NAME, mall.getCnCityName());
            mallValues.put(TableContract.Building.COLUMN_CITY_NAME_PY, mall.getPyCityName());
            mallValues.put(TableContract.Building.COLUMN_BUILDING_CODE, mall.getBuildingCode());
            mallValues.put(TableContract.Building.COLUMN_BUILDING_NAME, mall.getCnName());
            mallValues.put(TableContract.Building.COLUMN_BUILDING_NAME_PY, mall.getPyName());
            databaseHelp.insert(mallValues, TableContract.Building.TABLE_NAME);
        }
    }

    private void addCitiesToDB() {
        for (Map.Entry<String, String> entry : cityMap.entrySet()) {
            ContentValues cityValues = new ContentValues();
            cityValues.put(TableContract.City.COLUMN_CITY_NAME_PY, entry.getKey());
            cityValues.put(TableContract.City.COLUMN_CITY_NAME, entry.getValue());

            databaseHelp.insert(cityValues, TableContract.City.TABLE_NAME);
        }
    }

    @NonNull
    private List<Mall> getMallsFromHttp(JSONArray data) throws JSONException {
        List<Mall> malls = new ArrayList<Mall>();
        for (int i = 0, len = data.length(); i < len; i++) {
            JSONObject mallObject = data.getJSONObject(i);

            // 判断城市
            String cityNameEn = mallObject.getString("pyCityName");
            if (!cityMap.containsKey(cityNameEn)) {
                cityMap.put(cityNameEn, mallObject.getString("cnCityName"));
            }

            //商场列表
            Mall mall = new Mall();
            mall.setCnCityName(mallObject.getString("cnCityName"));
            mall.setPyCityName(mallObject.getString("pyCityName"));
            mall.setBuildingCode(mallObject.getString("buildingCode"));
            mall.setCnName(mallObject.getString("cnName"));
            mall.setPyName(mallObject.getString("pyName"));
            malls.add(mall);
        }
        return malls;
    }

    public List<Map<String, Object>> getCityList() {
        return cityList;
    }
}
